package servlets.invitation;

import hibernate.method.RelationMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class RelationDelete
 */
@WebServlet("/RelationDelete")
public class RelationDelete extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RelationDelete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
		
		String friend_id = (String)request.getParameter("check");
		
		String user_id = (String) request.getParameter("user_id");
	
		int user = Integer.parseInt(user_id);
		
		int friend = Integer.parseInt(friend_id);
	
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		RelationMethods rel_m = new RelationMethods();
	
		
	
		if(rel_m.findRelationToFrom(sessionFactory, session, user, friend) !=null || rel_m.findRelationToFrom(sessionFactory, session, user, friend).size()!=0){
		System.err.println("tofrom");
		session.delete(rel_m.findRelationToFrom(sessionFactory, session, user, friend).get(0));
		} else if(rel_m.findRelationFromTo(sessionFactory, session, user, friend) !=null|| rel_m.findRelationFromTo(sessionFactory, session, user, friend).size()!=0){
			System.err.println("fromto");
		session.delete(rel_m.findRelationFromTo(sessionFactory, session, user, friend).get(0));
		}
		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Znajomosc zostala usunieta\"); window.location.href = \"social/index.jsp?page=friends&group=currentFriends\";</script>");
			
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"Znajomosc nie zapostala usunieta\"); window.location.href = \"social/index.jsp?page=friends&group=currentFriends\";</script>");
			
		}
	}

}
